<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
      <!-- <div class="title-gra plr30">
        <div class="grab gra-r">
          <span class="grab gra-l"></span>
        </div>
      </div> -->

      <div v-loading="loading" class="authorityHeight">
        <TabSystemsyAuthority :view="view" :isSystemAuthority="isSystemAuthority" ref="TabSystemsyAuthority" />

        <div style="margin: 20px 0 20px 0;">
          <div class="title-gra authorityDiv">
            <span style="color:#0090ff">查看非资源目录数据</span>
            <span class="right">
              <i :class="zymlflag ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" @click="zymlflagOpen"></i>
            </span>
            <!-- <div class="grab gra-r"></div> -->
          </div>
          <div v-show="zymlflag">
            <div style="margin: 20px 40px 20px 40px">
              <el-radio-group v-model="resourceAuthorityValue" :disabled="view">
                <el-radio :label="1" v-if="!view">是</el-radio>
                <el-radio :label="0" v-if="!view">否</el-radio>
                <el-radio :label="1" v-if="view && resourceAuthorityValue==1">是</el-radio>
                <el-radio :label="0" v-if="view && resourceAuthorityValue==0">否</el-radio>
              </el-radio-group>
            </div>
            <div class="mr-btn mt-20">
              <el-button v-if="!view" type="primary" @click="saveResourceAuthority">确定</el-button>
            </div>
          </div>
        </div>


        <TabDataType v-if="!view" :roleId="roleId" :view="view" ref="tabDataType" />

        <TabDataTypeView v-if="view" :roleId="roleId" :view="view" ref="tabDataType" />

        <div style="margin: 20px 0 20px 0">
          <div class="title-gra authorityDiv">
            <span style="color:#0090ff">数据分级权限</span>
            <span class="right">
              <i :class="sjfjflag ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" @click="sjfjflagOpen"></i>
            </span>
            <!-- <div class="grab gra-r"></div> -->
          </div>
          <div v-show="sjfjflag">
            <div style="margin: 20px 40px 20px 40px">
              <el-form :model="ruleForm" ref="ruleForm" label-width="0px">
                <el-form-item>
                  <span>数据分级：</span>
                  <el-select v-model="authorityLevelValue" style="width:50%" placeholder="请选择" :disabled="view">
                    <el-option v-for="(item, index) in dataLevelOptions" :key="index" :label="item.dataName"
                      :value="item.dataValue"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div class="mr-btn">
              <el-button v-if="!view && dataLevelOptions.length!=0" type="primary" @click="saveDataLevel">确定</el-button>
            </div>
          </div>
        </div>

        <TabDataSources class="mt-20" :roleId="roleId" :view="view" :isBusiness="isBusiness" ref="tabDataSources" />

        <TabServiceCategory class="mt-20" :roleId="roleId" :view="view" :isBusiness="isBusiness"
          ref="tabServiceCategory" />

        <FieldRelations class="mt-20" :roleId="roleId" :view="view" :isBusiness="isBusiness" ref="fieldRelations" />
        <div style="margin: 20px 0 20px 0">
          <div class="title-gra authorityDiv">
            <span style="color:#0090ff">是否脱敏</span>
            <span class="right">
              <i :class="sftmflag ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" @click="sftmflagOpen"></i>
            </span>
            <!-- <div class="grab gra-r"></div> -->
          </div>
          <div v-show="sftmflag">
            <div style="margin: 20px 40px 20px 40px">
              <el-radio-group v-model="sftmAuthorityValue" :disabled="isShowRadio">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
              <!-- <el-radio-group v-model="sftmAuthorityValue" :disabled="view">
                <el-radio :label="1" v-if="!view">是</el-radio>
                <el-radio :label="0" v-if="!view">否</el-radio>
                <el-radio :label="1" v-if="view && sftmAuthorityValue==1">是</el-radio>
                <el-radio :label="0" v-if="view && sftmAuthorityValue==0">否</el-radio>
              </el-radio-group> -->
            </div>
            <div style="margin: 20px 40px 20px 40px;display: flex;justify-content:start;align-items: center;"
              v-show="sftmAuthorityValue">
              <span>选择字段：</span>
              <el-input placeholder="是：请选择脱敏字段" style="width:70%" v-model="tmAuthorityText" :disabled="true">

              </el-input>
              <el-button v-if="isShowButton" type="primary" icon="el-icon-plus"
                style="margin-left: 20px;padding-top: 0px;color:#ffffff" circle @click="setMetaData()"></el-button>
            </div>
            <div class="mr-btn mt-20">
              <el-button v-if="!view" type="primary" @click="saveftmAuthorityValue">确定</el-button>
            </div>
          </div>
        </div>
      </div>
      <metaDataDialog ref="metaDataDialog" v-on:setMeta="getMetaData"></metaDataDialog>
    </el-dialog>
  </div>
</template>

<script>
  import {
    queryAllauthority,
    queryRolesauthority,
    queryUserauthority,
    resourceAuthority,
    systemDict,
    saveDataLevel,
    getResourceContentAuthority,
    getDataLevel
  } from "@/api/authority.js";

  import TabSystemsyAuthority from "./TabSystemsyAuthority";
  import TabDataType from "./TabDataType";
  import TabDataSources from "./TabDataSources";
  import TabServiceCategory from "./TabServiceCategory";
  import FieldRelations from "./FieldRelations";
  import TabDataTypeView from "./TabDataTypeView";
  import metaDataDialog from "@/views/authorityManage/metaDataDialog";
  import {
    addUserDesensitize,
    getUserDesensitize
  } from "@/api/roleApi.js";
  export default {
    name: "authorityManageDialog",
    data() {
      return {
        title: "权限设置",
        loading: false,
        dialogVisible: false,
        tabPosition: "系统操作权限",
        authorityInfo: {},
        resData: {},
        resDataCheck: {},
        tmInfoArray: [],
        isShowButton: true,
        isShowRadio: false,
        currentIndex: 1,
        isSystemAuthority: {
          listValue: [],
          checkValue: []
        },
        isDbAthority: {
          listValue: [],
          checkValue: []
        },
        isBusiness: {
          listValue: [],
          checkValue: []
        },
        resourceAuthorityValue: "",
        authorityLevelValue: "",
        dataLevelOptions: [],
        ruleForm: {},
        zymlflag: true,
        sjfjflag: true,
        roleId: "",
        view: false,
        sftmflag: true,
        sftmAuthorityValue: false,
        tmAuthorityText: "" //脱敏字段
      };
    },
    components: {
      TabSystemsyAuthority,
      TabDataType,
      TabDataSources,
      TabServiceCategory,
      FieldRelations,
      TabDataTypeView,
      metaDataDialog
    },
    watch: {},
    methods: {
      setMetaData() {
        this.$refs.metaDataDialog.openDialog(this.roleId, this.tmAuthorityText, this.tmInfoArray);
      },
      openDialog(val) {
        this.authorityInfo = val;
        this.dialogVisible = true;
        this.tmAuthorityText = "";
        if (val.from == "user") {
          this.roleId = val.roles[0].roleId;
        } else {
          this.roleId = val.id;
        }

        if (val.type == "view") {
          this.title = "权限查看";
          this.isShowButton = false;
          this.isShowRadio = true;
          this.view = true;
          this.$nextTick(() => {
            this.getResourceContentAuthority();
            this.getDataLevel();
            this.getTMDataInfo();
            this.$refs.tabDataType.getResourceAuthority("1");
            this.$refs.tabDataSources.roleAuthResCategory();
            this.$refs.tabServiceCategory.getRoleFieldCategories();
            this.$refs.fieldRelations.getRoleFieldConnections();
          });
        } else {
          this.view = false;
          this.title = "权限设置";
          this.isShowButton = true;
          this.isShowRadio = false;
          this.authorityLevelValue = "";
          this.resourceAuthorityValue = "";
          this.$nextTick(() => {
            this.getDataLevel();
            this.$refs.tabDataType.getDataAreaAll();
            this.$refs.tabDataSources.getAllResourceType();
            this.$refs.tabServiceCategory.getFieldCategories();
            this.$refs.fieldRelations.getFieldConnections();
            this.getResourceContentAuthority();
            this.getTMDataInfo();
            this.$refs.TabSystemsyAuthority.getSystemList(val.id);
          });
        }
        switch (val.from) {
          case "user":
            this.initUserata(val.id, val.type == "view");
            break;
          case "roles":
            this.initRolesData(val.id, val.type == "view");
            break;
          default:
            break;
        }
      },
      getMetaData(data) {
        this.tmInfoArray = [];
        this.tmAuthorityText = "";
        this.tmInfoArray = data;
        for (let i = 0; i < data.length; i++) {
          this.tmAuthorityText += data[i].zwmc + ";"
          //  this.tmAuthorityText += data[i]+ ";"
        }
        // selectTmText
        // this.schemaMappingDTOList[this.currentIndex].newColumnName = data.bsf ? data.bsf : this.schemaMappingDTOList[
        //   this.currentIndex].newColumnName;
        // this.schemaMappingDTOList[this.currentIndex].newColumnType = data.sjlx ? data.sjlx : this.schemaMappingDTOList[
        //   this.currentIndex].newColumnType;
        // this.schemaMappingDTOList[this.currentIndex].orgColumnComment = data.sm ? data.sm : this.schemaMappingDTOList[
        //   this.currentIndex].orgColumnComment;
      },
      handleClose() {
        this.clearAll();
      },
      initUserata(id, ifView) {
        this.loading = true;
        queryUserauthority(id)
          .then(res => {
            this.resDataCheck = res;
            this.isSystemAuthority.listValue = res.systemAuthority;
            this.isSystemAuthority.checkValue = res.systemAuthority;
            this.isDbAthority.listValue = res.systemAuthority;
            this.isDbAthority.checkValue = res.systemAuthority;
            this.isSystemAuthority.ifView = ifView;
            this.isDbAthority.ifView = ifView;
            this.$nextTick(() => {
              this.tabPosition = "系统操作权限";
              this.loading = false;
              this.$nextTick(() => {
                this.$refs.TabSystemsyAuthority.init();
              });
            });
          })
          .catch(err => {
            this.loading = false;
            this.$message.error(err);
          });
      },
      initRolesData(id, ifView) {
        this.loading = true;
        if (ifView) {
          queryRolesauthority(id)
            .then(res => {
              this.resDataCheck = res;
              this.isSystemAuthority.listValue = res.systemAuthority;
              this.isSystemAuthority.checkValue = res.systemAuthority;
              this.isDbAthority.listValue = res.systemAuthority;
              this.isDbAthority.checkValue = res.systemAuthority;
              this.isSystemAuthority.ifView = ifView;
              this.isDbAthority.ifView = ifView;
              this.$nextTick(() => {
                this.tabPosition = "系统操作权限";
                this.loading = false;
                this.$nextTick(() => {
                  this.$refs.TabSystemsyAuthority.init();
                });
              });
            })
            .catch(err => {
              this.loading = false;
              this.$message.error(err);
            });
        } else {
          Promise.all([queryAllauthority(), queryRolesauthority(id)])
            .then(res => {
              this.resData = res[0];
              this.resDataCheck = res[1];

              this.isSystemAuthority.listValue = res[0].sysAuthority;
              this.isSystemAuthority.checkValue = this.processSysData(
                res[1].systemAuthority
              );
              this.isSystemAuthority.ifView = ifView;
              this.isSystemAuthority.id = id;
              this.isDbAthority.listValue = res[0].dataAuthority;
              this.isDbAthority.checkValue = res[1].dataAuthority;
              this.isDbAthority.ifView = ifView;
              this.isDbAthority.id = id;

              this.$nextTick(() => {
                this.tabPosition = "系统操作权限";
                this.loading = false;
                this.$nextTick(() => {
                  this.$refs.TabSystemsyAuthority.init();
                });
              });
            })
            .catch(err => {
              this.$message.error(err);
            });
        }
      },
      processSysData(data) {
        let checkdataArr = [];
        if (data.length > 0) {
          data.forEach(element => {
            if (element.nodeFlag == 1) {
              checkdataArr.push(element);
            }
          });
        }

        return checkdataArr;
      },
      clearAll() {
        this.resData = [];
        this.resDataCheck = [];
        this.isSystemAuthority = {
          listValue: [],
          checkValue: [],
          ifView: ""
        };
        this.isDbAthority = {
          listValue: [],
          checkValue: [],
          ifView: ""
        };
        this.isBusiness = {
          listValue: [],
          checkValue: [],
          ifView: ""
        };
        this.tabPosition = "";
        this.view = !this.view;
        this.resourceAuthorityValue = "";
        this.dialogVisible = false;
      },
      zymlflagOpen() {
        this.zymlflag = !this.zymlflag;
      },
      sjfjflagOpen() {
        this.sjfjflag = !this.sjfjflag;
      },
      sftmflagOpen() {
        this.sftmflag = !this.sftmflag;
      },
      //添加非资源目录
      saveResourceAuthority(id) {
        const params = {
          roleId: this.roleId,
          additionAuthorityFlag: this.resourceAuthorityValue
        };
        resourceAuthority(params)
          .then(res => {
            if (!res.success) {
              this.$message.error(res.message);
            } else {
              this.$message.success("保存查看非资源目录数据成功");
            }
          })
          .catch(res => {
            this.$message.error(res.message);
          });
      },
      //获取对应角色的非资源目录信息
      getResourceContentAuthority() {
        getResourceContentAuthority(this.roleId).then(res => {
          if (res.success) {
            this.resourceAuthorityValue = res.data ? 1 : 0;
          }
        });
      },
      //获取所有数据分级
      getdataLevelAll() {
        systemDict("SJJLMGJB").then(res => {
          if (res.success) {
            this.dataLevelOptions = res.data[0].info;
          }
        });
      },
      //获取脱敏信息
      getTMDataInfo() {
        getUserDesensitize(this.roleId).then(res => {
          if (res) {
            if (res.desensizeColumns.length > 0) {
              this.tmInfoArray = [];
              this.sftmAuthorityValue = true;
              for (let i = 0; i < res.desensizeColumns.length; i++) {
                this.tmAuthorityText += res.desensizeColumns[i].zwmc + ";"
                let obj = {};
                obj.bsf = res.desensizeColumns[i].bsf;
                obj.zwmc = res.desensizeColumns[i].zwmc;
                this.tmInfoArray.push(obj);
              }
            }else {
                this.tmInfoArray = [];
                this.sftmAuthorityValue = false;
            }
          }
        });

      },
      //保存数据分级权限
      saveDataLevel() {
        const params = {
          roleId: this.roleId,
          dataLevel: this.authorityLevelValue
        };
        saveDataLevel(params)
          .then(res => {
            if (!res.success) {
              this.$message.error(res.message);
            } else {
              this.$message.success("保存数据分级权限成功");
            }
          })
          .catch(res => {
            this.$message.error(res.message);
          });
      },
      //获取对应角色的分级权限
      getDataLevel() {
        this.getdataLevelAll();
        getDataLevel(this.roleId).then(res => {
          if (res.success && res.data) {
            this.authorityLevelValue = res.data.dataLevel;
          }
        });
      },
      //保存数据是否脱敏
      saveftmAuthorityValue() {
        let tmObject = {
          roleid: this.roleId
        };
        tmObject.fields = [];
        if (this.sftmAuthorityValue == false) {
          tmObject.fields = [];
          this.tmInfoArray = [];
          this.tmAuthorityText = "";
        } else {
          if(this.tmInfoArray.length==0) {
               this.$message.error("用户提交失败,请选择脱敏字段后在进行保存");
               return;
          };
          if(this.tmInfoArray.length>100) {
               this.$message.error("脱敏字段不能超过100个");
               return;
          };
          for (let i = 0; i < this.tmInfoArray.length; i++) {
            let tmObj = {};
            tmObj.bsf = this.tmInfoArray[i].bsf;
            tmObj.zwmc = this.tmInfoArray[i].zwmc;
            tmObject.fields.push(tmObj);
          }
        }
        // let jsonStr = JSON.stringify(tmObject);
        addUserDesensitize(tmObject).then(res => {
          if (res) {
            this.$message.success("保存脱敏成功");
          }
        });

      }
    }
  };

</script>
<style>
  .authorityHeight {
    height: auto;
    overflow: auto;
    padding: 20px;
  }

  .authorityDiv {
    height: 30px;
    margin-bottom: 20px;
    font-size: 16px;
  }

  .authorityDiv .right {
    float: right;
    cursor: pointer;
  }

</style>
